package com.cbgolf.oa.views;

import android.app.Activity;
import android.app.Dialog;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AbsListView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.Adp_Calendar;
import com.cbgolf.oa.base.BaseView;
import com.cbgolf.oa.presenter.IOrderPresenter;
import com.cbgolf.oa.entity.AccountOrderBean;
import com.cbgolf.oa.entity.BillUserBean;
import com.cbgolf.oa.entity.DateRange;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.util.PopUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.TypeUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import com.zhy.base.adapter.ViewHolder;
import com.zhy.base.adapter.abslistview.CommonAdapter;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by lq on 2017/11/4.
 */

public class OrderListView extends BaseView implements Adp_Calendar.IResultWorker,
    SwipeRefreshLayout.OnRefreshListener {

  //top
  @ViewInject(R.id.topBack_ll)
  private View topBack;
  @ViewInject(R.id.title_tv)
  private TextView topTitle;
  //
  @ViewInject(R.id.a_orderlist_calendar_ll)
  private View calendarView;
  @ViewInject(R.id.date_tv)
  private TextView dateTv;
  @ViewInject(R.id.a_orderlist_filter_ll)
  private View filterView;
  @ViewInject(R.id.a_orderlist_filter_tv)
  private TextView filterTv;
  @ViewInject(R.id.a_orderlist_swiperefreshlayout)
  private SwipeRefreshLayout refreshLayout;
  @ViewInject(R.id.a_orderlist_listview)
  private ListView listView;
  //
  private ErrorView errorView;
  private List<AccountOrderBean> listData = new ArrayList<>();
  private CommonAdapter<AccountOrderBean> adapter;

  @Override
  public void backResult(Object obj) {
    if (null != dialogCalendar && dialogCalendar.isShowing()) {
      dialogCalendar.dismiss();
    }
    DateRange bean = null;
    try {
      bean = (DateRange) obj;
    } catch (Exception e) {

    }
    if (null == bean) {
      return;
    }
    year = bean.year;
    month = bean.month;
    day = bean.day;
    worker.getData(DateUtil.dateToStamp(year + "-" + month + "-" + day + " " + "00:00:00"));
    dateTv.setText(year + "年" + month + "月" + day + "日");
  }

  @Override
  public void onRefresh() {
    worker.refresh();
  }

  public IOrderPresenter worker;

  public OrderListView(Activity act, IOrderPresenter worker) {
    this.worker = worker;
    ViewUtils.autoInjectAllField(this, act);
    super.init(act);
  }

  @Override
  protected void findViews() {
    errorView = new ErrorView(context);
  }

  @Override
  protected void setViews() {
    topTitle.setText(TextUtil.Text(worker.getActivityTitle()));
    refreshLayout.setColorSchemeResources(R.color.bg_blue, R.color.text_gray,
        R.color.white, R.color.bg_blue);
//        refreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
//                android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
    refreshLayout.setDistanceToTriggerSync(300);// 设置手指在屏幕下拉多少距离会触发下拉刷新
    refreshLayout.setSize(SwipeRefreshLayout.LARGE);
    refreshLayout
        .setProgressBackgroundColorSchemeColor(ContextCompat.getColor(context, R.color.white));
    adapter = new CommonAdapter<AccountOrderBean>(context, R.layout.item_order, listData) {
      @Override
      public void convert(ViewHolder holder, final AccountOrderBean bean) {
        holder.setText(R.id.item_order_time_tv,
            DateUtil.stampToDate(bean.recordDate, DateUtil.formatYMD));
        holder.setText(R.id.item_order_cardnum_tv, TextUtil.Text(bean.cardNo));
        holder.setText(R.id.item_order_userid_tv, TextUtil.Text(bean.identityName));
        holder.setText(R.id.item_order_state_tv,
            (Util.isEquals(bean.status, "CHECKOUTED")) ? "已结账" : "未结账");
        holder.setText(R.id.item_order_name_tv, TextUtil.Text(bean.name));
        holder.setText(R.id.item_order_dengjiren_tv, TextUtil.Text(bean.creatorName));
        holder.setText(R.id.item_order_paymoney_username_tv, TextUtil.Text(bean.cashPerson));
        holder.setText(R.id.item_order_money_tv,
            "￥" + TextUtil.textNumFloat(TypeUtil.parseFloat(bean.totalCost)));
        holder.setOnClickListener(R.id.item_order_details_tv,
            v -> worker.showOrderDetails(bean.customerId));

      }
    };
    listView.setAdapter(adapter);
    refreshLayout.setOnRefreshListener(this);
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(System.currentTimeMillis());
    year = c.get(Calendar.YEAR);
    month = c.get(Calendar.MONTH) + 1;
    day = c.get(Calendar.DAY_OF_MONTH);
    dateTv.setText(year + "年" + month + "月" + day + "日");
  }


  @Override
  protected void setListener() {
    topBack.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        context.finish();
      }
    });
    calendarView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        showCalendar();
      }
    });
    filterView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (getUserFail) {
          Util.show("很抱歉，签单人没有获取成功");
          return;
        }
        if (isNoUser) {
          Util.show("暂无其他签单人信息");
          return;
        }
        final List<BillUserBean> list = new ArrayList<>();
        String name = filterTv.getText().toString();
        if (!Util.isEquals("全部", name)) {
          BillUserBean bean = new BillUserBean();
          bean.name = "全部";
          bean.identifier = "";
          list.add(bean);
        }
        for (int i = 0; i < listUsers.size(); i++) {
          list.add(listUsers.get(i));
        }
        PopUtil.showUserList(context, filterView, list, new PopUtil.ItemClickListener() {
          @Override
          public void click(int position) {
            filterTv.setText(list.get(position).name);
            worker.getDataByUserId(list.get(position).identifier);
          }
        });
      }
    });
    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
      @Override
      public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (listView.getAdapter() != null && listView.getLastVisiblePosition() == (
            listView.getAdapter().getCount() - 1)
            && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
          worker.loadMore();
        }
      }

      @Override
      public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
          int totalItemCount) {

      }
    });

  }

  private int tempYear;
  private int tempMonth;
  private int year;
  private int month;
  private int day;
  Dialog dialogCalendar;

  private void showCalendar() {
    dialogCalendar = new Dialog(context, R.style.mDialog);
    View view = context.getLayoutInflater().inflate(R.layout.dialog_calendar_phone, null);
    View layout = view.findViewById(R.id.dialog_calendar_layout_ll);
    View before = view.findViewById(R.id.dialog_calendar_before_ll);
    View after = view.findViewById(R.id.dialog_calendar_after_ll);
    final TextView title = (TextView) view.findViewById(R.id.dialog_calendar_title_tv);
    final GridView gridView = (GridView) view.findViewById(R.id.dialog_calendar_gridview);
    AutoUtil.auto(view);
    dialogCalendar.setContentView(view);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    final int curYear = calendar.get(Calendar.YEAR);
    final int curMonth = calendar.get(Calendar.MONTH) + 1;
//        year = calendar.get(Calendar.YEAR);
//        month = calendar.get(Calendar.MONTH) + 1;
    tempYear = year;
    tempMonth = month;
    title.setText(month + "月 " + year + "年");
    final Adp_Calendar adapterCalendar = new Adp_Calendar(context, year, month, day, this);
    gridView.setAdapter(adapterCalendar);
    after.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        tempMonth = tempMonth + 1;
        if (tempMonth > 12) {
          tempMonth = 1;
          tempYear += 1;
        }
        title.setText(tempMonth + "月 " + tempYear + "年");
        adapterCalendar.clear();
        adapterCalendar.setData(tempYear, tempMonth);
        adapterCalendar.upDataUI();
      }
    });
    before.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        tempMonth = tempMonth - 1;
        if (tempMonth == 0) {
          tempMonth = 12;
          tempYear = tempYear - 1;
        }
//                if (tempYear < curYear || (tempYear == curYear && tempMonth < curMonth)) {
//                    tempMonth += 1;
//                    if (tempMonth > 12) {
//                        tempMonth = 1;
//                        tempYear += 1;
//                    }
//                    return;
//                }
        title.setText(tempMonth + "月 " + tempYear + "年");
        adapterCalendar.clear();
        adapterCalendar.setData(tempYear, tempMonth);
        adapterCalendar.upDataUI();
      }
    });

    dialogCalendar.show();


  }

  @Override
  public void showProgress() {
    if (!refreshLayout.isRefreshing()) {
      AnimaUtil.showLoading(context, errorView.getLoadingTv());
    }
  }

  @Override
  public void stopProgress() {
    if (null != refreshLayout) {
      refreshLayout.setRefreshing(false);
    }
    AnimaUtil.stopLoading();
  }

//    public void showError(String msg) {
//        if (Util.listIsNull(listData)) {
//            errorView.showError(refreshLayout, msg, () -> worker.reLoad());
//        }
//    }

  @Override
  public void getDataFail(String msg) {
    getDataFail(msg, -1);
  }

  @Override
  public void getDataFail(String msg, int code) {
    if (Util.listIsNull(listData) && null != errorView) {
      errorView.showError(refreshLayout, msg, code, () -> worker.reLoad());
    }
  }

  public void showData(Object obj) {
    stopProgress();
    List<AccountOrderBean> list = null;
    try {
      list = (List<AccountOrderBean>) obj;
    } catch (Exception e) {

    }
    if (Util.listIsNull(list)) {
      getDataFail("此日期暂无签单数据");
      return;
    }
    refreshLayout.setVisibility(View.VISIBLE);
    listData.clear();
    listData.addAll(list);
    adapter.notifyDataSetChanged();
  }

  public void loadMoreSuccess(Object obj) {

    List<AccountOrderBean> list = null;
    try {
      list = (List<AccountOrderBean>) obj;
    } catch (Exception e) {

    }
    if (Util.listIsNull(list)) {
      return;
    }
    refreshLayout.setVisibility(View.VISIBLE);
    listData.addAll(list);
    adapter.notifyDataSetChanged();
  }

  public void getUserListFail(String msg) {
    getUserFail = true;
  }

  private boolean getUserFail;
  private boolean isNoUser;
  List<BillUserBean> listUsers = new ArrayList<>();

  public void getUserlistSuccess(Object obj) {

    getUserFail = false;
    List<BillUserBean> list = null;
    try {
      list = (List<BillUserBean>) obj;
    } catch (Exception e) {

    }
    if (Util.listIsNull(list)) {
      isNoUser = true;
      return;
    }
    listUsers.clear();
    listUsers.addAll(list);

  }

  public void getDataByDateFail(String msg) {

    if (null != errorView) {
      errorView.showError(refreshLayout, msg, () -> worker.reLoad());
    }
  }

  public void getDataByDateSuccess(Object obj) {
    List<AccountOrderBean> list = null;
    try {
      list = (List<AccountOrderBean>) obj;
    } catch (Exception e) {

    }
    if (Util.listIsNull(list)) {
      getDataByDateFail("此日期暂无签单数据");
      return;
    }
    refreshLayout.setVisibility(View.VISIBLE);
    listData.clear();
    listData.addAll(list);

    adapter.notifyDataSetChanged();
  }

  public void getDataByUserFail(String msg) {
    if (null != errorView) {
      errorView.showError(refreshLayout, msg, () -> worker.reLoad());
    }
  }

  public void getDataByUserSuccess(Object obj) {
    List<AccountOrderBean> list = null;
    try {
      list = (List<AccountOrderBean>) obj;
    } catch (Exception e) {

    }
    if (Util.listIsNull(list)) {
      getDataByUserFail("此签单人暂无签单数据");
      return;
    }
    refreshLayout.setVisibility(View.VISIBLE);
    listData.clear();
    listData.addAll(list);
    adapter.notifyDataSetChanged();
  }


}
